package com.xcdh.ittools.utils;

import com.api.ittools.entity.ToolDatasource;
import com.xcdh.ittools.config.ITToolConfiguration;
import com.xcdh.ittools.sql.ITToolBoundSql;
import com.xcdh.ittools.type.ITToolExecutor;
import com.xcdh.ittools.type.ITToolReturnType;
import com.xcdh.ittools.wrapper.DBColumnWrapper;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class MysqlDbUtil {


    public static Connection getConnection(ToolDatasource ds){
        // 加载 JDBC 驱动程序
        try {
            Class.forName(ds.getDriverClass());
            Connection conn = DriverManager.getConnection(ds.getDsUrl(), ds.getUsername(), ds.getPassword());
            return conn ;
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }

    }
    public static void closeResource(AutoCloseable ...closeables){
        for (AutoCloseable closeable : closeables) {
            try {
                closeable.close();
            } catch (Exception e) {
                log.error("资源关闭异常：{}",e.getMessage());
            }
        }
    }


    public static List<DBColumnWrapper> getDBColumnWrapper(ResultSetMetaData metaData) throws SQLException {
        List<DBColumnWrapper> wrapper = new ArrayList<>() ;
        int columnCount = metaData.getColumnCount();
        for(int i =1 ; i<=columnCount ;i++){
            String columnName = metaData.getColumnName(i);
            String columnLabel = metaData.getColumnLabel(i);
            int columnType = metaData.getColumnType(i);
            wrapper.add(new DBColumnWrapper(columnType , columnLabel , columnName)) ;
        }
        return wrapper ;
    }

    public static <T> T query(String sql ,ToolDatasource ds, ITToolReturnType result, Object parameter ){
        ITToolConfiguration itToolConfiguration = new ITToolConfiguration(ds , result);
        ITToolBoundSql boundSql = new ITToolBoundSql(itToolConfiguration , sql  , parameter) ;
        ITToolExecutor itToolExecutor = new ITToolExecutor(itToolConfiguration , boundSql) ;
        return itToolExecutor.query() ;
    }
}
